package com.dlz.systemshop.service.impl;

import com.dlz.systemshop.pojo.LogUser;
import com.alibaba.fastjson.JSON;
import com.dlz.systemshop.pojo.User;
import com.dlz.systemshop.service.UserService;
import com.dlz.systemshop.utils.JwtUtils;
import lombok.experimental.Accessors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author 董熠涛
 * @date 2025/4/26 00:48
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public String login(User user) {
//        UsernamePasswordAuthenticationToken：这是Spring Security提供的一个类，用于封装用户名和密码，以便进行身份验证。
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
//        authenticationManager：这是一个 AuthenticationManager 接口的实现，负责执行实际的认证逻辑。
        Authentication authenticate = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
        if (authenticate == null){
            throw new RuntimeException("登录失败");
        }
//        如果用户名和密码验证通过，并将 UserDetails 对象设置为该 Authentication 对象的 principal 属性。
        LogUser principal = (LogUser) authenticate.getPrincipal();
        String jsonString = JSON.toJSONString(principal);
        String token = JwtUtils.generateToken(jsonString, 1000L * 60 * 60);

        stringRedisTemplate.opsForValue().set("token_"+token,token, 60 * 60, TimeUnit.SECONDS);

        return token;
    }
}
